package com.dp.appi.util;


import com.dp.appi.exception.SendSMSException;

import java.util.Date;
import java.util.Random;

/**
 * Created by xiaoji on 2015/11/23.
 */
public class ValidCode {
    private String validcode;
    private Date createTime;
    private static int expire=5*60*1000;//过期时间
    private static int limitTime=60*1000;//限制发送间隔时间

    public static void setValidCode(String phone,String code){
        ValidCode validCode = new ValidCode();
        validCode.setCreateTime(new Date());
        validCode.setValidcode(code);
//        ContextHolderUtils.getSession().setAttribute(phone,validCode);
        ContextHolderUtils.getApplication().setAttribute(phone,validCode);
    }

    public static ValidCode getValidCode(String phone){
//        return (ValidCode)ContextHolderUtils.getSession().getAttribute(phone);
        return (ValidCode)ContextHolderUtils.getApplication().getAttribute(phone);
    }

    /**
     * 验证码是否正确
     * @return
     */
    public static boolean isCorrectValidCode(String key,String code){
        ValidCode validCode = getValidCode(key);
        Date nowDate = new Date();
        long nowt = nowDate.getTime();
        if(validCode!=null){
            long old = validCode.getCreateTime().getTime();
            if(nowt-old <= expire){
                if(validCode.getValidcode().equals(code)){
                    ContextHolderUtils.getApplication().removeAttribute(key);
                    return true;
                }else{
                    throw new SendSMSException(SYS.SMS002.name());
                }
            }else{
                throw new SendSMSException(SYS.SMS003.name());
            }
        }
        return false;
    }

    /**
     * 验证码是否正确
     * @return
     */
    public static boolean validCodeLimit(String phone){
        ValidCode validCode = getValidCode(phone);
        Date nowDate = new Date();
        long nowt = nowDate.getTime();
        if(validCode!=null){
            long old = validCode.getCreateTime().getTime();
            if(nowt-old >= limitTime){
               return true;
            }else{
               return false;
            }
        }else {
            return true;
        }
    }

    public static String getRandomCode(){
        return ""+(new Random().nextInt(899999)+100000);
    }
    public String getValidcode() {
        return validcode;
    }

    public void setValidcode(String validcode) {
        this.validcode = validcode;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public static void main(String[] args) {
        System.out.println(getRandomCode());
    }
}
